/**
 * Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering, 
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 *GENERATED USING SOFTWARE.
 */
package cgl.narada.wsinfra.apps;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.Properties;
import java.util.StringTokenizer;

import javax.xml.soap.SOAPMessage;

import cgl.narada.wsinfra.deployment.Filter;
import cgl.narada.wsinfra.deployment.FilterPipeline;
import cgl.narada.wsinfra.deployment.FilterPipelineFactory;
import cgl.narada.wsinfra.deployment.NetworkSubstrate;
import cgl.narada.wsinfra.deployment.ServiceMessageListener;
import cgl.narada.wsinfra.deployment.impl.NBNetworkSubstrate;
import cgl.narada.wsinfra.exception.DeploymentException;
import cgl.narada.wsinfra.exception.MessageFlowException;
import cgl.narada.wsinfra.exception.ProcessingException;
import cgl.narada.wsinfra.messaging.bootstrap.InitializationFactory;
import cgl.narada.wsinfra.messaging.bootstrap.Initializer;
import cgl.narada.wsinfra.messaging.entity.Subscriber;
import cgl.narada.wsinfra.messaging.interactions.SubscriberWithPublisher;
import cgl.narada.wsinfra.messaging.interactions.SubscriberWithSubscriptionManager;
import cgl.narada.wsinfra.messaging.interactions.WseSubscriberWithSubscriptionManager;
import cgl.narada.wsinfra.messaging.widget.Subscription;
import cgl.narada.wsinfra.schemas.addressing.EndpointReferenceType;
import cgl.narada.wsinfra.schemas.soap.EnvelopeDocument;
import cgl.narada.wsinfra.util.SoapEnvelopeConversion;
import cgl.narada.wsinfra.util.SoapPrinter;
import cgl.narada.wsinfra.wsa.WsaEnvelopeCreator;
import cgl.narada.wsinfra.wsa.WsaEprCreator;
import cgl.narada.wsinfra.wsa.WsaProcessingFactory;

public class MessagingSubscriber implements ServiceMessageListener {
  private NetworkSubstrate networkSubstrate;
  private FilterPipelineFactory filterPipelineFactory;
  private FilterPipeline filterPipeline;
  private WsaEprCreator wsaEprCreator;
  private WsaEnvelopeCreator wsaEnvelopeCreator;
  private SoapEnvelopeConversion soapEnvelopeConversion;
  
  private Filter loggingFilter, subscriberFilter;
  private boolean isEventing = true;
  private String subscriberAddress;
  private EndpointReferenceType subscriberEPR;
  private Subscriber subscriber;
  private SubscriberWithPublisher subscriberPublisherInteraction;
  private SubscriberWithSubscriptionManager subscriberSubMgrInteraction;
  
  private String moduleName = "WseSinkEndpoint: ";

  public MessagingSubscriber(String subscriberAddress, Properties networkProperties) 
    throws DeploymentException {
    this.subscriberAddress = subscriberAddress;
    
    wsaEprCreator = WsaProcessingFactory.getWsaEprCreator();
	 wsaEnvelopeCreator = WsaProcessingFactory.getWsaEnvelopeCreator();
	 soapEnvelopeConversion = SoapEnvelopeConversion.getInstance();
    
	 subscriberEPR = wsaEprCreator.createEpr(this.subscriberAddress);
	 initializeSubscriber();
	 initializeDeploymentEnvironment(networkProperties);
  }

  
  private void initializeSubscriber() throws DeploymentException {
		InitializationFactory initializationFactory =
			InitializationFactory.getInstance();
		Initializer initializer = initializationFactory.newInitializer(isEventing);
		subscriber = initializer.createSubscriber(subscriberEPR);
		subscriberPublisherInteraction = subscriber.getInteractionWithPublisher();
		subscriberSubMgrInteraction = subscriber.getInteractionWithSubscriptionManager();
	}
  
  private void initializeDeploymentEnvironment(Properties networkProperties)
	throws DeploymentException {
	  filterPipelineFactory =  FilterPipelineFactory.getInstance();
	  filterPipeline = filterPipelineFactory.newFilterPipeline("WsePipeline");
	  loggingFilter = new LoggingFilter();
	  filterPipeline.addFilter(loggingFilter);
	  subscriberFilter = new SubscriberFilter();
	  filterPipeline.addFilter(subscriberFilter);
			  
	  networkSubstrate = new NBNetworkSubstrate();
	  networkSubstrate.configureNetworking(networkProperties);
	    
	  networkSubstrate.registerPipeline(filterPipeline);
	  filterPipeline.registerNetworkSubstrate(networkSubstrate);	  
  }
  
  
  public void onMessage(SOAPMessage soapMessage) {
    System.out.println(moduleName + "Received SOAP Message from the " +
		       "underlying infrastructure");
    printSoapMessage(soapMessage);
  }

  public void onException(Exception exception) {


  }

 

  public void printSoapMessage(SOAPMessage soapMessage) {
    String soapMsg = null;
    try {
      soapMsg = SoapPrinter.getStringRepresentation(soapMessage);
    } catch (Exception e) {
      System.out.println(moduleName + "Problems printing SOAPMessage"); 
    }
    System.out.println(soapMsg);
  }

  
  public String createLinkTo(Properties props, String linkType) 
    throws DeploymentException { 
    if (networkSubstrate == null) {
      System.out.println(moduleName + "The network substrate is null");
    }
    String linkId = 
      ( (NBNetworkSubstrate)networkSubstrate).createLinkTo(props, linkType);
    return linkId;
  }


  public void sendSOAPMessage(SOAPMessage soapMessage) 
    throws DeploymentException, MessageFlowException, ProcessingException {
    filterPipeline.processMessageFromApplication(soapMessage); 
  }


  public void issueSubscribeRequest(String publisherAddress, String subscriptionType) 
    throws ProcessingException, MessageFlowException  {
    
    EndpointReferenceType publisherEPR = wsaEprCreator.createEpr(publisherAddress);
    String deliveryMode = "http://schemas.xmlsoap.org/ws/2004/08/eventing/DeliveryModes/Push";
    String topicFilterDialect = "http://www.naradabrokering.org/TopicMatching";
    String regExFilterDialect = "http://www.naradabrokering.org/RegularExpressionMatching";

    String xpathFilterDialect = "http://www.w3.org/TR/1999/REC-xpath-19991116";
    String xqueryFilterDialect = "http://www.w3.org/TR/2004/WD-xquery-20041029";
    String topicFilterConstraint = "/Literature/Shakespere";
    String regExFilterConstraint = "[Tt]he [Qq]uick [Bb]rown [Ff]ox [Jj]umps";

    String xpathFilterConstraint = "declare namespace c1='http://www.naradabrokering.org/catalog'" + "$this//c1:catalog/c1:cd/c1:price > 20";
    

    String nsText = "declare namespace po = 'http://openuri.org/easypo'";
    String pathText = "$this//po:purchase-order/po:line-item";
    
    String queryText = nsText + pathText;
    String xqueryFilterConstraint = queryText;

    String filterConstraint = topicFilterConstraint;
    String filterDialect = topicFilterDialect;

    if (subscriptionType.equals("topic")) {
      filterConstraint = topicFilterConstraint;
      filterDialect = topicFilterDialect;
    }

    if (subscriptionType.equals("regex")) {
      filterConstraint = regExFilterConstraint;
      filterDialect = regExFilterDialect;
    }

    if (subscriptionType.equals("xpath")) {
      filterConstraint = xpathFilterConstraint;
      filterDialect = xpathFilterDialect;
    }

    if (subscriptionType.equals("xquery")) {
      filterConstraint = xqueryFilterConstraint;
      filterDialect = xqueryFilterDialect;
    }
    
    Calendar expiresAt = Calendar.getInstance();
    expiresAt.add(Calendar.MONTH, 1);

    EnvelopeDocument envelopeDocument = 
       subscriberPublisherInteraction.createSubscribe(publisherEPR, filterDialect, 
      			 													filterConstraint, expiresAt);
    
    String report = moduleName + "The CREATED Subscription Request is\n" +
      envelopeDocument.toString();
    System.out.println(report);
    subscriberPublisherInteraction.issueExchange(envelopeDocument);
  }
  

  public void issueGetStatusRequest(String subscriptionIdentifier) 
    throws ProcessingException, MessageFlowException {
	  
	  if (!subscriberSubMgrInteraction.isEventing()) {
		  throw new ProcessingException(moduleName + 
				  "This operation is NOT supported in WS-Notification");
	  }
	  
	  WseSubscriberWithSubscriptionManager wseSubscriberWithSubMgrInteraction =
		  (WseSubscriberWithSubscriptionManager) subscriberSubMgrInteraction;
	  
    EnvelopeDocument envelopeDocument = 
     wseSubscriberWithSubMgrInteraction.createGetStatus(subscriptionIdentifier);
    
    String report = moduleName + "The CREATED GetStatus Request is\n" +
      envelopeDocument.toString();
    System.out.println(report);

    subscriberSubMgrInteraction.issueExchange(envelopeDocument);
  }


  public void issueRenewRequest(String subscriptionIdentifier) 
    throws ProcessingException, MessageFlowException {
    Calendar expiresAt = Calendar.getInstance();
    expiresAt.add(Calendar.MONTH, 2);
    EnvelopeDocument envelopeDocument = 
      subscriberSubMgrInteraction.createRenew(subscriptionIdentifier, expiresAt);
    String report = moduleName + "The CREATED Renew Request is\n" +
      envelopeDocument.toString();
    System.out.println(report);
    
    subscriberSubMgrInteraction.issueExchange(envelopeDocument);
  }


  public void issueUnsubscribeRequest(String subscriptionIdentifier) 
    throws ProcessingException, MessageFlowException {
   
    EnvelopeDocument envelopeDocument = 
   	 subscriberSubMgrInteraction.createUnsubscribe(subscriptionIdentifier);
    String report = moduleName + "The CREATED Unsubscribe Request is\n" +
      envelopeDocument.toString();
    System.out.println(report);

    subscriberSubMgrInteraction.issueExchange(envelopeDocument);
    
  }

  public void listSubscriptionIdentifiers() {
		Enumeration e = subscriber.getListOfSubscriptionIdentifiers();
		String report = "The list of registered subscription identifiers are: \n";
		while (e.hasMoreElements()) {
			String id = (String) e.nextElement();
			report += (id + "\n");
		}
		System.out.println(report);
	}
	
	public void printSubscriptionInfo(String subscriptionIdentifier) throws ProcessingException {
		Subscription subscription = subscriber.getSubscription(subscriptionIdentifier);
		String report = "The subscription info is as follows: \n" + subscription.toString();
		System.out.println(report);
	}

  public static void main(String[] args) {
    if (args.length != 2) {
			String errorReport = "Usage: java cgl.narada.wsinfra.apps.WseSinkEndpoint "
										+ "[hostname] [TCPServerPort] ";
			System.out.println(errorReport);
			System.exit(0);
		}

		String hostname = args[0];
		String port = args[1];
		Properties props = new Properties();
		props.put("TCPServerPort", port);

		BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer tok;
		String cmd;

		try {
			String sinkAddress = "tcp://" + hostname + ":" + port;
			MessagingSubscriber endpoint = new MessagingSubscriber(sinkAddress,
					props);
			System.out.println("Listening to TCP communications on port [" + port
										+ "]. \n Type h for help on commands");
			while (true) {
				cmd = r.readLine();

				if (cmd == null) {
					System.out.println("Terminating program ....");
					break;
				}

				if (cmd.startsWith("h")) {
					System.out.println("Create Link \t\t-> cr hostname portNum ");
					System.out.println("Subscribe   \t\t-> sub [publisherAddress] <subType = [t][r][x][q]>");
					System.out.println("List subscription IDs \t-> l ");
					System.out.println("Print SubscriptionInfo\t-> p [subscriptionId] ");
					System.out.println("GetStatus   \t\t-> status [subscriptionId]");
					System.out.println("Renew       \t\t-> renew [subscriptionId]");
					System.out.println("UnSubscribe \t\t-> unsub [subscriptionId]");
					System.out.println("Command-list\t\t-> h]");
				}

				if (cmd.startsWith("cr")) {
					tok = new StringTokenizer(cmd, " ");
					if (tok.countTokens() != 3) {
						System.out.println("The format of the Create Link request is listed below");
						System.out.println("Create Link \t\t-> cr hostname portNum ");
						continue;
					}
					tok.nextToken(); /* skipping the token "cr" */
					Properties linkProps = new Properties();
					linkProps.put("hostname", tok.nextToken());
					linkProps.put("portnum", tok.nextToken());
					String _linkId = endpoint.createLinkTo(linkProps, "tcp");
					System.out.println("Created link with id => " + _linkId);
				}
				/** end create link */

				if (cmd.startsWith("sub")) {
					tok = new StringTokenizer(cmd, " ");
					if (tok.countTokens() != 3) {
						System.out.println("The format of the Subscription request is listed below");
						System.out.println("Subscribe   \t\t-> sub [publisherAddress] <subType = [t][r][x][q]>");
						continue;
					}
					tok.nextToken(); /* skipping the token "sub" */
					String publisherAddress = tok.nextToken();
					String subscriptionType = "topic";
					String widget = tok.nextToken();
					if (widget.startsWith("t")) {
						subscriptionType = "topic";
					}
					if (widget.startsWith("x")) {
						subscriptionType = "xpath";
					}
					if (widget.startsWith("r")) {
						subscriptionType = "regex";
					}
					if (widget.startsWith("q")) {
						subscriptionType = "xquery";
					}

					endpoint.issueSubscribeRequest(publisherAddress, subscriptionType);
				}

				if (cmd.startsWith("status")) {
					tok = new StringTokenizer(cmd, " ");
					if (tok.countTokens() != 2) {
						System.out.println("The format of the GetStatus request is listed below");
						System.out.println("GetStatus   \t\t-> status [subscriptionId]");
						continue;
					}
					tok.nextToken(); /* skipping the token "status" */
					String subscriptionIdentifier = tok.nextToken();
					endpoint.issueGetStatusRequest(subscriptionIdentifier);
				}

				if (cmd.startsWith("renew")) {
					tok = new StringTokenizer(cmd, " ");
					if (tok.countTokens() != 2) {
						System.out.println("The format of the Renew request is listed below");
						System.out.println("Renew       \t\t-> renew [subscriptionId]");
						continue;
					}
					tok.nextToken(); /* skipping the token "renew" */
					String subscriptionIdentifier = tok.nextToken();
					endpoint.issueRenewRequest(subscriptionIdentifier);
				}

				if (cmd.startsWith("unsub")) {
					tok = new StringTokenizer(cmd, " ");
					if (tok.countTokens() != 2) {
						System.out.println("The format of the Unsubscribe request is listed below");
						System.out.println("UnSubscribe \t\t-> unsub [subscriptionId]");
						continue;
					}
					tok.nextToken(); /* skipping the token "unsub" */
					String subscriptionIdentifier = tok.nextToken();
					endpoint.issueUnsubscribeRequest(subscriptionIdentifier);
				}

				if (cmd.startsWith("l")) {
					endpoint.listSubscriptionIdentifiers();
				}

				if (cmd.startsWith("p")) {
					tok = new StringTokenizer(cmd, " ");
					if (tok.countTokens() != 2) {
						System.out.println("The correct usage of the Print Subscription Info is listed below");
						System.out.println("Print SubscriptionInfo-> p [subscriptionId] ");
						continue;
					}
					tok.nextToken(); /* skipping the token "p" */
					String subscriptionId = tok.nextToken();
					endpoint.printSubscriptionInfo(subscriptionId);
				}

			} /* end while(true) */

		} catch (Exception ioe) {
			ioe.printStackTrace();
		} /* end try-catch */
	}/*end main() */

}
